#include "FreeWayReceiver.h"
#include "FreeWayEntry.h"
#include "FreeWayMgr.h"
#define BUFSIZE 1024




FreeWayReceiver::FreeWayReceiver( FreeWayMgr* mptr)
{

    m_mgrPtr = mptr;

    //entry = new FreeWayEntry();
    run = true;
}





void FreeWayReceiver::svc()
{
   //entry->init();
   LOG(INFO) <<"Receiver thread joined " ;

   char buff[BUFSIZE];
   char ipBuff[20];
   int nBytes = 0;
   int type = 0;
   while(run)
   {

      nBytes = entry->fwRecv(buff,BUFSIZE,ipBuff);

      if(nBytes > 0)
      {
        //normal message is passed to brain module

        if(  (type = parseHead(buff)) != 0  ){




            LOG(INFO) <<"received buffer: " << buff;



            if(type == NORMALMSG){

                entry->fwSend((FreeWayMgr::m_freewayResp).c_str(),(FreeWayMgr::m_freewayResp).size());
                //m_proPtr->pushData(buff + (FreeWayMgr::m_freewayId).size(),nBytes);



                //pass message to brain
                freeway2Brain_data(brain, buff , nBytes);



            }
            else if(type == LOGINMSG)
            {
                std::string strIp(ipBuff);
                bzero(ipBuff, 20);

                LOG(INFO) << "new client: " << strIp;

                client c = entry->getCliAddr();
                std::string name = getUserInfo(buff);

                m_mgrPtr->addClient(name, c);

            }

        }


        else
            LOG(INFO) <<"invalid MSG!";
      }

      //recover
      nBytes = 0;
      type = 0;
      bzero(buff, BUFSIZE);
   }

}





std::string FreeWayReceiver::getUserInfo(const char * buf)
{
    int offset = (FreeWayMgr::m_freeWayAccess).size();
    const char * content = buf + offset;
    std::string msg(content);
    //find split comma ","
    int pos = msg.find(',');
    std::string sub = msg.substr(0,pos );
    return sub;

}








int FreeWayReceiver::parseHead(const char * buf)
{
    if(strncmp(buf,(FreeWayMgr::m_freewayId).c_str(),(FreeWayMgr::m_freewayId).size()) == 0)
    {
        return NORMALMSG;
    }
    else if(strncmp(buf,(FreeWayMgr::m_freeWayAccess).c_str(),(FreeWayMgr::m_freeWayAccess).size()) == 0)
    {
        return LOGINMSG;
    }

    return ERRORMSG;

}

FreeWayReceiver::~FreeWayReceiver()
{
    //delete entry;
    //entry = 0;
}
